package cn.z2huo.usercenter.management.app.controller.user;

import cn.z2huo.usercenter.management.app.service.user.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * @author z2huo
 */
@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserServiceImpl userService;

    @GetMapping("/user/exportAllUser")
    public ResponseEntity<byte[]> exportAllUserExcel() throws UnsupportedEncodingException {

//        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        // 这里URLEncoder.encode可以防止中文乱码 当然和e asyexcel没有关系
//        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());

        byte[] bytes = userService.exportAllUserExcel();

//        String fileName = URLEncoder.encode("用户列表.xlsx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        String fileName = "用户列表.xlsx";
//        String fileName = URLEncoder.encode("用户列表.xlsx", StandardCharsets.UTF_8).replace("+", "%20");

        ContentDisposition contentDisposition = ContentDisposition.attachment()
                .filename(fileName, StandardCharsets.UTF_8)
                .build();

        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CONTENT_ENCODING, "UTF-8");
        headers.setContentDisposition(contentDisposition);
//        headers.setContentDispositionFormData(HttpHeaders.CONTENT_DISPOSITION, fileName);

        ResponseEntity<byte[]> body = ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .contentLength(bytes.length)
                .body(bytes);

        return body;
    }

}
